package com.pd.dao;

import com.pd.kit.LogUtil;
import com.pd.pojo.WxAccount;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by dong peng
 * DATE : 2017/2/26
 * TIME : 23:11.
 */

public class SessionManager {

    private String resource = "";
    private SqlSessionFactory sqlSessionFactory = null;
    private static final Class CLASS_LOCK = SessionManager.class;

    private SessionManager() {

    }

    public void setResource(String resource) {
        this.resource = resource;
    }

    /**
     * 保持sqlSessionFactory单列模式，加类级锁同步
     *
     * @return
     */
    public SqlSessionFactory iniSqlSessionFactory(){
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            LogUtil.error("加载mybatis的配置文件失败： ", e);
        }
        synchronized (CLASS_LOCK) {
            if(sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }
        }
        return sqlSessionFactory;
    }

    /**
     * 打开SqlSession
     *
     * @return
     */
    public SqlSession openSqlSession() {
        if(sqlSessionFactory == null) {
            iniSqlSessionFactory();
        }

        return sqlSessionFactory.openSession();
    }
}
